﻿using System.ComponentModel.DataAnnotations;

namespace GMS.NET.Web.Components.Shared.Global.Attributes
{
    /// <summary>
    /// 通用自定义验证类
    /// </summary>
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter,
    AllowMultiple = false)]
    public class FormVaildationAttribute : DataTypeAttribute
    {
        private readonly Func<object, ValidationContext, (bool status, string errorMsg)> _validationDelegate;
        private ValidationContext _validationContext;
        public FormVaildationAttribute(Func<object, ValidationContext, (bool status, string errorMsg)> validationDelegate) : base(DataType.Custom)
        {
            this._validationDelegate = validationDelegate;
            _validationContext = null!;
        }
        protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
        {
            _validationContext = validationContext;
            return base.IsValid(value, validationContext);
        }
        public override bool IsValid(object? value)
        {
            var checkFunc = _validationDelegate(value!, _validationContext);
            this.ErrorMessage = checkFunc.errorMsg;
            return checkFunc.status;
        }
    }
    public class FormVaildationResult
    {
        /// <summary>
        /// 表单验证返回成功
        /// </summary>
        public static  (bool status, string errorMsg) Success { get; } = (true, string.Empty);
    }
}
